package com.yx.yinshanjinniu.activitys;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yx.yinshanjinniu.R;
import com.yx.yinshanjinniu.adapters.FollowOrderAdapter;
import com.yx.yinshanjinniu.adapters.RollingTextAdapter;
import com.yx.yinshanjinniu.base.BaseActivity;
import com.yx.yinshanjinniu.bean.FollowOrderBean;
import com.yx.yinshanjinniu.bean.FollowOrderRequestBean;
import com.yx.yinshanjinniu.bean.GifBean;
import com.yx.yinshanjinniu.bean.SellOrderInfoBean;
import com.yx.yinshanjinniu.constants.Constant;
import com.yx.yinshanjinniu.eventbus.EventCenter;
import com.yx.yinshanjinniu.eventbus.EventConstants;
import com.yx.yinshanjinniu.net.ActionCallbackListener;
import com.yx.yinshanjinniu.utils.GlideUtils;
import com.yx.yinshanjinniu.utils.RouteUtil;
import com.yx.yinshanjinniu.utils.ToastUtil;
import com.yx.yinshanjinniu.utils.Utils;
import com.yx.yinshanjinniu.view.CreateOrderModule;
import com.yx.yinshanjinniu.view.LevelPopupWindow;
import com.yx.yinshanjinniu.view.MarqueeTextView;
import com.yx.yinshanjinniu.view.ProGroupBeanPopupWindow;
import com.yx.yinshanjinniu.view.TextViewSwitcher;
import com.zc.mychart.model.GoodsAllBean;
import com.zc.mychart.utils.ArithUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FollowOrderCenterActivity extends BaseActivity implements View.OnClickListener, LevelPopupWindow.LevelPopupListener, ProGroupBeanPopupWindow.ProGroupListener {
    private SmartRefreshLayout refresh_layout;
    private RelativeLayout rl_notice;
    private TextViewSwitcher ts_notice;
    private LinearLayout ll_my_follow_order, ll_my_follow, ll_follow_rule, ll_choose_level, ll_choose_product;
    private RadioGroup rg_group;
    private TextView tv_all, tv_time, tv_level_name, tv_choose_product, tv_empty;
    private ImageView iv_guide;
    private LinearLayout rl_choose;
    private RecyclerView rv_list;
    private List<FollowOrderBean> mFollowOrderList;
    private FollowOrderRequestBean mRequestBean;
    private FollowOrderAdapter followOrderAdapter;
    private List<SellOrderInfoBean> mBarrageList;
    private int mPageIndex = 1;
    private LevelPopupWindow chooseLevelWindow;
    private ProGroupBeanPopupWindow chooseWindow;
    private GoodsAllBean mGroupBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getFollowOrderList();
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_follow_order_center;
    }

    @Override
    protected void findViews() {
        refresh_layout = findViewById(R.id.refresh_layout);
        rl_notice = findViewById(R.id.rl_notice);
        ts_notice = findViewById(R.id.ts_notice);
        ll_my_follow_order = findViewById(R.id.ll_my_follow_order);
        ll_my_follow = findViewById(R.id.ll_my_follow);
        ll_follow_rule = findViewById(R.id.ll_follow_rule);
        rg_group = findViewById(R.id.rg_group);
        rl_choose = findViewById(R.id.rl_choose);
        tv_all = findViewById(R.id.tv_all);
        tv_time = findViewById(R.id.tv_time);
        ll_choose_level = findViewById(R.id.ll_choose_level);
        tv_level_name = findViewById(R.id.tv_level_name);
        ll_choose_product = findViewById(R.id.ll_choose_product);
        tv_choose_product = findViewById(R.id.tv_choose_product);
        rv_list = findViewById(R.id.rv_list);
        tv_empty = findViewById(R.id.tv_empty);
        iv_guide = findViewById(R.id.iv_guide);

    }

    @Override
    protected void setListeners() {
        refresh_layout.setEnableLoadMore(true);
        refresh_layout.setEnableRefresh(true);
        ll_my_follow_order.setOnClickListener(this);
        ll_my_follow.setOnClickListener(this);
        ll_follow_rule.setOnClickListener(this);
        ll_choose_product.setOnClickListener(this);
        ll_choose_level.setOnClickListener(this);
        tv_all.setOnClickListener(this);
        tv_time.setOnClickListener(this);
        iv_guide.setOnClickListener(this);
        rl_notice.setOnClickListener(this);

        refresh_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPageIndex = 1;
                getFollowOrderList();
            }
        });

        refresh_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPageIndex++;
                getFollowOrderList();
            }
        });

        rg_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_follow_order:
                        mPageIndex = 1;
                        mRequestBean.follow = false;
                        break;
                    case R.id.rb_my_follow:
                        mPageIndex = 1;
                        mRequestBean.follow = true;
                }
                getFollowOrderList();
            }
        });
    }


    @Override
    public void onClick(View v) {
        if (v == ll_my_follow_order) {
            if (isUserValidLogin())
                RouteUtil.toMyFollowOrderActivity(this);
        } else if (v == ll_my_follow) {
            if (isUserValidLogin()) {
                RouteUtil.toFollowListActivity(this);
            }
        } else if (v == ll_follow_rule) {
            RouteUtil.toWebViewActivity(this, Constant.H5_FOLLOW_RULE);
        } else if (v == ll_choose_product) {
            if (null == chooseWindow) {
                chooseWindow = new ProGroupBeanPopupWindow((BaseActivity) mContext, this);
            }
            int[] location = new int[2];
            rl_choose.getLocationOnScreen(location);
            chooseWindow.showAsDropDown(rl_choose);
        } else if (v == ll_choose_level) {
            if (null == chooseLevelWindow) {
                chooseLevelWindow = new LevelPopupWindow((BaseActivity) mContext, this);
            }
            int[] location1 = new int[2];
            rl_choose.getLocationOnScreen(location1);
            chooseLevelWindow.showAsDropDown(rl_choose);
        } else if (v == tv_all) {
            changeStatus(0);

            if (null != chooseLevelWindow) {
                chooseLevelWindow.resetChoose();
            }
            if (null != chooseWindow) {
                chooseWindow.resetChoose();
            }

            mRequestBean.openTime = false;
            mRequestBean.follow = false;
            mRequestBean.level = "";
            mRequestBean.contract = "";

            getFollowOrderList();
        } else if (v == tv_time) {
            changeStatus(1);

            mRequestBean.openTime = true;
            getFollowOrderList();
        } else if (v == iv_guide){
            RouteUtil.routePageByUrl((BaseActivity) mContext, myApplication.getGifMap().get("4").link);
        } else if (v == rl_notice){
            //牛单播报
            RouteUtil.gotoActivity(mContext, CattleBillActivity.class,null);
        }
    }

    private void changeStatus(int status) {
        if (status == 1) {
            tv_all.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
//            tv_time.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_3e56ff));
            tv_time.setBackgroundResource(R.drawable.shape_line_4dp_fd7e26);
            tv_all.setBackgroundResource(R.drawable.shape_4dp_eaeaeb);
        } else if (status == 2) {
            tv_all.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
//            tv_level_name.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_3e56ff));
            tv_all.setBackgroundResource(R.drawable.shape_4dp_eaeaeb);
            ll_choose_level.setBackgroundResource(R.drawable.shape_line_4dp_fd7e26);
        } else if (status == 3) {
            tv_all.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
//            tv_choose_product.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_3e56ff));
            tv_all.setBackgroundResource(R.drawable.shape_4dp_eaeaeb);
            ll_choose_product.setBackgroundResource(R.drawable.shape_line_4dp_fd7e26);
        } else {
//            tv_all.setTextColor(ContextCompat.getColor(mContext, R.color.color_text_3e56ff));
            tv_time.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
            tv_level_name.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
            tv_choose_product.setTextColor(ContextCompat.getColor(mContext, R.color.color_5b6066));
            tv_time.setBackgroundResource(R.drawable.shape_4dp_eaeaeb);
            ll_choose_level.setBackgroundResource(R.drawable.shape_4dp_eaeaeb);
            ll_choose_product.setBackgroundResource(R.drawable.shape_4dp_eaeaeb);
            tv_all.setBackgroundResource(R.drawable.shape_line_4dp_fd7e26);

            tv_choose_product.setText("品种");
            tv_level_name.setText("等级");
        }
    }

    public void initData() {
        mFollowOrderList = new ArrayList<>();
        mRequestBean = new FollowOrderRequestBean();

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        rv_list.setLayoutManager(layoutManager);
        followOrderAdapter = new FollowOrderAdapter();
        followOrderAdapter.setFollowOrderListener(new FollowOrderAdapter.FollowOrderListener() {
            @Override
            public void onClickDetail(String userId) {
                RouteUtil.toFollowOrderUserActivity((BaseActivity) mContext, userId);
            }

            @Override
            public void onClickFollow(int position) {
                if (mFollowOrderList == null || mFollowOrderList.isEmpty()) return;
                if (isUserValidLogin()) {
                    //更新用户信息
                    myApplication.updateUserDetail();
                    FollowOrderBean bean = mFollowOrderList.get(position);
                    mGroupBean = myApplication.getAllGoodMap().get(bean.pro_code);
                    if (null != mGroupBean) {
                        CreateOrderModule.getInstance().createOrder((BaseActivity) mContext, bean.trade_type, bean.order_id, mGroupBean, bean.unit_price, bean.user_id, 0);
                    } else {
                        ToastUtil.showToast(mContext, "未获取的产品信息");
                    }
                }
            }

            @Override
            public void onClickGoKLine(int position) {
                if (mFollowOrderList == null || mFollowOrderList.isEmpty()) return;

                FollowOrderBean bean = mFollowOrderList.get(position);
                GoodsAllBean mGroupBean = myApplication.getAllGoodMap().get(bean.pro_code);
                RouteUtil.toMarketActivity((BaseActivity) mContext, mGroupBean.pro_code);
            }
        });
        rv_list.setAdapter(followOrderAdapter);

        GifBean gifBean = myApplication.getGifMap().get("4");
        if (gifBean != null && !TextUtils.isEmpty(gifBean.img)) {
            GlideUtils.showImageFitxyOptions(mContext, gifBean.img, iv_guide);
            iv_guide.setVisibility(View.VISIBLE);
        } else {
            iv_guide.setVisibility(View.GONE);
        }

        getProfitNewList();
    }

    public void getProfitNewList() {
        mAppAction.getOrderSquare(new ActionCallbackListener<List<SellOrderInfoBean>>() {
            @Override
            public void onSuccess(List<SellOrderInfoBean> data) {
                mBarrageList = data;

                if (null != mBarrageList && mBarrageList.size() > 0) {
                    rl_notice.setVisibility(View.VISIBLE);

                    ts_notice.setAdapter(new RollingTextAdapter() {
                        @Override
                        public int getCount() {
                            return mBarrageList.size() > 0 ? mBarrageList.size() : 0;
                        }

                        @Override
                        public View getView(Context context, View contentView, int position) {
                            View view = View.inflate(context, R.layout.item_notice_scroll, null);
                            MarqueeTextView tv_report = view.findViewById(R.id.it_tv);

                            SellOrderInfoBean bean = mBarrageList.get(position);
                            String title = "";
                            title += "恭喜 " + bean.nick_name + " ";
                            title += bean.pro_name + "增益";
                            title += "<font color=\"#E2524D\"> " + ArithUtil.format(Double.valueOf(bean.pro_loss)) + "元</font>";
                            Utils.setHtmlText(tv_report, title);
                            return view;
                        }
                    });
                    ts_notice.setOnItemClickListener(new TextViewSwitcher.OnItemClickListener() {
                        @Override
                        public void onClick(int position) {
//                            RouteUtil.toFollowOrderUserActivity(FollowOrderCenterActivity.this, mBarrageList.get(position).getUser_id());
                        }
                    });

                    if (mBarrageList.size() > 1) {
                        ts_notice.startFlipping();
                    }
                } else {
                    rl_notice.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                rl_notice.setVisibility(View.GONE);
            }
        });
    }

    public void getFollowOrderList() {
        mAppAction.getFollowList(mPageIndex, mRequestBean.openTime, mRequestBean.contract, mRequestBean.follow, mRequestBean.level, new ActionCallbackListener<List<FollowOrderBean>>() {
            @Override
            public void onSuccess(List<FollowOrderBean> data) {
                completeRefresh();

                if (mPageIndex == 1) {
                    if (data != null && data.size() > 0) {
                        mFollowOrderList = data;
                    } else {
                        mFollowOrderList.clear();
                    }
                } else {
                    if (data != null && data.size() > 0) {
                        mFollowOrderList.addAll(data);
                    }
                }

                if (data.size() == 10) {
                    refresh_layout.setEnableLoadMore(true);
                } else {
                    refresh_layout.setEnableLoadMore(false);
                }


                if (mFollowOrderList.size() > 0) {
                    tv_empty.setVisibility(View.GONE);
                } else {
                    tv_empty.setVisibility(View.VISIBLE);
                }

                updateOrderList();

            }

            @Override
            public void onFailure(String errorCode, String message) {
                completeRefresh();
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    /**
     * 关闭刷新加载
     */
    private void completeRefresh() {
        refresh_layout.finishRefresh(1000);
        refresh_layout.finishLoadMore(1000);
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        super.onEventComming(eventCenter);
        int event = eventCenter.getEventCode();
        switch (event) {
            case EventConstants.EVENTCODE_UPDATE_PRO_PRICE:
                updateOrderList();

                //开始更新列表
                Map<String, GoodsAllBean> allGoodMap = myApplication.getAllGoodMap();
                if (null != mGroupBean && allGoodMap.get(mGroupBean.pro_code) != null && CreateOrderModule.getInstance().getOrderCreateDialog().isShowing()) {
                    CreateOrderModule.getInstance().setNewPrice();
                }
                break;
        }
    }

    private void updateOrderList() {
        followOrderAdapter.setDataList(Utils.completionFollow(mFollowOrderList));
    }

    @Override
    public void onClickLevel(String name, int level) {
        tv_level_name.setText(name);

        changeStatus(2);

        mRequestBean.level = String.valueOf(level);
        getFollowOrderList();
    }

    @Override
    public void onClickProduct(String name, String code) {
        tv_choose_product.setText(name);

        changeStatus(3);

        mRequestBean.contract = code;
        getFollowOrderList();
    }

}